package pres.liko.blackapi.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import pres.liko.blackapi.event.BlackApiChangeEvent;
import pres.liko.blackapi.service.BlackApiService;
import pres.liko.iot.api.CacheOpenfrignClient;
import pres.liko.iot.bean.R;
import pres.liko.iot.bean.Validates;
import reactor.core.publisher.Mono;

import java.util.Set;

/**
 * @ClassName: CacheConfig
 * @Auther: liko
 * @Description:
 * @Date: 2022/11/2 21:57
 */
@Component
public class CacheConfig {


    private BlackApiService blackApiService;
    private CacheOpenfrignClient cacheOpenfrignClient;
    private StreamBridge streamBridge;

    @Autowired
    public CacheConfig(BlackApiService blackApiService, CacheOpenfrignClient cacheOpenfrignClient, StreamBridge streamBridge) {
        this.blackApiService = blackApiService;
        this.cacheOpenfrignClient = cacheOpenfrignClient;
        this.streamBridge = streamBridge;
    }

    // @PostConstruct
    public void init() {
        // 加载黑名单
        Mono<R<Set<String>>> allEnable = blackApiService.findAllEnable();
        // 保存到redis
        allEnable.subscribe(setR -> {
            cacheOpenfrignClient.sAddMembers(Validates.APIS.getStr(), setR.getData())
                    .subscribe(
                            // 只需通知网关更新即可，无需传递数据
                            aLong -> streamBridge.send("blackapi_exchange", "")
                    );
        });
    }

    @EventListener
    public void onEvent(ContextRefreshedEvent event) {
        init();
    }

    // 发生更新事件，就来更新缓存
    @EventListener
    public void onIpChange(BlackApiChangeEvent event) {
        // 先删除，在重新加载到redis,由init内部通知网关
        cacheOpenfrignClient.deleteKeys(Validates.APIS.getStr())
                .subscribe(aLong -> init());
    }

}